class User < ApplicationRecord
  attr_accessor :remember_token
  before_save { self.username = username.downcase }
  validates :username,
            presence: { message: '用户名不能为空'},
            length: { in:3..20 },
            uniqueness: {case_sensitive: false}
  validates :password,
            presence: { message: '密码不能为空'},
            length: { in:6..20 }
  validates :nickname,
            presence: { message: '昵称不能为空'}
            

  has_secure_password

  # 返回指定字符串的哈希摘要
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
               BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # 返回一个随机令牌
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end
end
